<template>
  <div class="reports">
    <div class="page-header">
      <h2>测试报告</h2>
      <el-button type="primary" @click="showGenerateDialog = true">
        <el-icon><Plus /></el-icon>
        生成报告
      </el-button>
    </div>

    <!-- 报告列表 -->
    <el-card>
      <el-table :data="reports" v-loading="loading" style="width: 100%">
        <el-table-column prop="name" label="报告名称" min-width="200" />
        <el-table-column prop="description" label="描述" min-width="300" />
        <el-table-column prop="total_cases" label="总用例数" width="100" />
        <el-table-column prop="passed_cases" label="通过" width="80">
          <template #default="scope">
            <el-tag type="success">{{ scope.row.passed_cases }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="failed_cases" label="失败" width="80">
          <template #default="scope">
            <el-tag type="danger">{{ scope.row.failed_cases }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="error_cases" label="错误" width="80">
          <template #default="scope">
            <el-tag type="danger">{{ scope.row.error_cases }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="success_rate" label="成功率" width="100">
          <template #default="scope">
            <el-progress 
              :percentage="scope.row.success_rate" 
              :color="getProgressColor(scope.row.success_rate)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="created_by_username" label="创建者" width="120" />
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewReport(scope.row)">查看</el-button>
            <el-button size="small" type="primary" @click="downloadReport(scope.row)">
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.page_size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 生成报告对话框 -->
    <el-dialog v-model="showGenerateDialog" title="生成测试报告" width="600px">
      <el-form :model="generateForm" :rules="formRules" ref="generateFormRef" label-width="120px">
        <el-form-item label="报告名称" prop="name">
          <el-input v-model="generateForm.name" placeholder="请输入报告名称" />
        </el-form-item>
        
        <el-form-item label="报告描述" prop="description">
          <el-input
            v-model="generateForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入报告描述"
          />
        </el-form-item>
        
        <el-form-item label="选择执行记录" prop="execution_ids">
          <el-transfer
            v-model="generateForm.execution_ids"
            :data="availableExecutions"
            :titles="['可选执行记录', '已选执行记录']"
            :props="{
              key: 'id',
              label: 'test_case_name'
            }"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showGenerateDialog = false">取消</el-button>
          <el-button type="primary" @click="generateReport" :loading="generating">
            生成报告
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看报告详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="报告详情" width="80%">
      <div v-if="selectedReport">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="报告名称">{{ selectedReport.name }}</el-descriptions-item>
          <el-descriptions-item label="创建者">{{ selectedReport.created_by_username }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(selectedReport.created_at) }}</el-descriptions-item>
          <el-descriptions-item label="成功率">
            <el-progress 
              :percentage="selectedReport.success_rate" 
              :color="getProgressColor(selectedReport.success_rate)"
            />
          </el-descriptions-item>
          <el-descriptions-item label="总用例数">{{ selectedReport.total_cases }}</el-descriptions-item>
          <el-descriptions-item label="通过用例数">
            <el-tag type="success">{{ selectedReport.passed_cases }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="失败用例数">
            <el-tag type="danger">{{ selectedReport.failed_cases }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="错误用例数">
            <el-tag type="danger">{{ selectedReport.error_cases }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">{{ selectedReport.description }}</el-descriptions-item>
        </el-descriptions>
        
        <div style="margin-top: 20px;" v-if="selectedReport.execution_details">
          <h4>执行详情</h4>
          <el-input
            v-model="executionDetailsJson"
            type="textarea"
            :rows="10"
            readonly
            font-family="monospace"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { reportAPI, executionAPI } from '@/api'

export default {
  name: 'Reports',
  setup() {
    const loading = ref(false)
    const generating = ref(false)
    const showGenerateDialog = ref(false)
    const showDetailDialog = ref(false)
    const selectedReport = ref(null)
    const reports = ref([])
    const availableExecutions = ref([])
    const generateFormRef = ref(null)

    const generateForm = reactive({
      name: '',
      description: '',
      execution_ids: []
    })

    const pagination = reactive({
      page: 1,
      page_size: 20,
      total: 0
    })

    const formRules = {
      name: [{ required: true, message: '请输入报告名称', trigger: 'blur' }],
      execution_ids: [{ required: true, message: '请选择执行记录', trigger: 'change' }]
    }

    const executionDetailsJson = computed(() => {
      if (!selectedReport.value?.execution_details) return ''
      return JSON.stringify(selectedReport.value.execution_details, null, 2)
    })

    const loadReports = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.page,
          page_size: pagination.page_size
        }
        const response = await reportAPI.getList(params)
        reports.value = response.results || []
        pagination.total = response.count || 0
      } catch (error) {
        console.error('加载报告列表失败:', error)
      } finally {
        loading.value = false
      }
    }

    const loadAvailableExecutions = async () => {
      try {
        const response = await executionAPI.getList({ page_size: 100 })
        availableExecutions.value = (response.results || []).map(item => ({
          id: item.id,
          test_case_name: `${item.test_case_name} (${item.status_display})`
        }))
      } catch (error) {
        console.error('加载执行记录失败:', error)
      }
    }

    const handleSizeChange = (size) => {
      pagination.page_size = size
      loadReports()
    }

    const handleCurrentChange = (page) => {
      pagination.page = page
      loadReports()
    }

    const viewReport = async (report) => {
      try {
        const response = await reportAPI.getDetail(report.id)
        selectedReport.value = response
        showDetailDialog.value = true
      } catch (error) {
        console.error('获取报告详情失败:', error)
      }
    }

    const downloadReport = (report) => {
      // 这里可以实现下载报告的逻辑
      ElMessage.info('下载功能待实现')
    }

    const generateReport = async () => {
      if (!generateFormRef.value) return
      
      try {
        await generateFormRef.value.validate()
        generating.value = true
        
        const response = await reportAPI.generate(generateForm)
        ElMessage.success('报告生成成功')
        showGenerateDialog.value = false
        loadReports()
        resetForm()
      } catch (error) {
        console.error('生成报告失败:', error)
      } finally {
        generating.value = false
      }
    }

    const resetForm = () => {
      Object.assign(generateForm, {
        name: '',
        description: '',
        execution_ids: []
      })
      if (generateFormRef.value) {
        generateFormRef.value.resetFields()
      }
    }

    const getProgressColor = (percentage) => {
      if (percentage >= 80) return '#67C23A'
      if (percentage >= 60) return '#E6A23C'
      return '#F56C6C'
    }

    const formatDate = (dateString) => {
      if (!dateString) return '-'
      return new Date(dateString).toLocaleString('zh-CN')
    }

    onMounted(() => {
      loadReports()
      loadAvailableExecutions()
    })

    return {
      loading,
      generating,
      showGenerateDialog,
      showDetailDialog,
      selectedReport,
      reports,
      availableExecutions,
      generateForm,
      generateFormRef,
      pagination,
      formRules,
      executionDetailsJson,
      loadReports,
      handleSizeChange,
      handleCurrentChange,
      viewReport,
      downloadReport,
      generateReport,
      getProgressColor,
      formatDate
    }
  }
}
</script>

<style scoped>
.reports {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 